package Compation;

public class numTeams {
    private int[] rating;

    public int numTeams(int[] rating) {
        if (rating == null || rating.length < 3) {
            return 0;
        }
        this.rating = rating;
        int length = rating.length;
        int res = 0;
        for (int i = 0; i < length - 2; i++) {
            for (int j = i + 2; j < length; j++) {
                if (Math.abs(rating[j] - rating[i]) < 2) {
                    continue;
                }
                for (int k = i + 1; k < j; k++) {
                    if (isValid(i, j, k)) {
                        res++;
                    }
                }
            }
        }
        return res;
    }

    private boolean isValid(int left, int right, int middle) {
        if (rating[middle] > rating[left] && rating[middle] < rating[right]) {
            return true;
        } else if (rating[middle] < rating[left] && rating[middle] > rating[right]) {
            return true;
        } else {
            return false;
        }
    }
}
